package top.milkbox.core;

import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 减少Servlet的数量，现在是一个功能一个Servlet，将其优化为一个模块一个Servlet，
 * 相当于在数据库中一张表对应一个Servlet，在Servlet中提供不同的方法，完成用户的请求。
 *
 * @author milkbox
 */
public class BaseServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String uri = req.getRequestURI();
        System.out.println("URI: " + uri);

        String methodName = uri.substring(uri.lastIndexOf("/") + 1);
        System.out.println("methodName: " + methodName);

        try {
            // 获取方法对象
            Method method = this.getClass().getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            System.out.println("当前方法所在的servlet：" + this.getClass().getSimpleName());
            // 执行方法
            System.out.println("将要执行方法：" + method.getName());
            method.invoke(this, req, resp);
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    /**
     * 将指定的object对象转为json字符串，并输出到response的输出流中
     */
    public void writeValue(Object object, HttpServletResponse response) throws IOException {
        response.setContentType("application/json;charset=utf-8");
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.writeValue(response.getWriter(), object);
    }

    /**
     * 将指定的object对象转为json字符串
     */
    public String writeValueAsString(Object object) throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        return objectMapper.writeValueAsString(object);
    }

    /**
     * 将指定的object对象转为json字符串，并输出到response的输出流中
     * 并在控制台打印日志信息
     */
    public void writeValueWithLog(Object object, HttpServletResponse response) throws IOException {

        response.setContentType("application/json;charset=utf-8");

        String json = writeValueAsString(object);
        response.getWriter().write(json);

        System.out.println("BaseServlet 打印的日志：");
        System.out.println(json);
    }


}
